package com.sky.controller.user;

import com.sky.constant.JwtClaimsConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.properties.JwtProperties;
import com.sky.result.Result;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.swagger.annotations.Api;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zcf
 */
@Api(tags = "用户相关接口")
@RestController
@RequestMapping("/user/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private JwtProperties jwtProperties;

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 用户小程序微信登录
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@RequestBody UserLoginDTO userLoginDTO) {
        // TODO 小程序登录
        User user = userService.login(userLoginDTO);
        //2.生成令牌
        Map<String, Object> map = new HashMap<>();
        map.put(JwtClaimsConstant.USER_ID, user.getId());
        String jwt = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), map);
        stringRedisTemplate.opsForValue().set("login_token_"+jwt,"cc",System.currentTimeMillis()+jwtProperties.getUserTtl(), TimeUnit.MICROSECONDS);
        //3.返回数据
        UserLoginVO userLoginVO = UserLoginVO.builder().token(jwt)
                .openid(user.getOpenid())
                .id(user.getId()).build();
        return Result.success(userLoginVO);
    }
}
